<?php

namespace App\Http\Controllers\Api;

use App\Model\AdminLog;
use App\Model\MsgHistory;
use App\Model\Number;
use App\Model\OperationLogs;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;

class CustomMsgController extends BaseController
{
    public function __construct(Request $request, MsgHistory $msgHistory)
    {
        parent::__construct($request);
        $this->model = $msgHistory;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {

        return $this->toJson(self::SUCCESS, $this->model->getList($request));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'uuid' => "required_if:all,0",
            'context' => 'required',
            'all' => ['bail','required', Rule::in(0,1)],
            'type' => [ 'bail', 'required', Rule::in(0, 1) ]
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }

        $link = $request->input('link', '') ?? '';
        $link_tip = $request->input('link_tip', '') ?? '';
        $msg = $this->model->createData([
            'user_id' => $request->input('uuid') ?: '全员',
            'context' => $request->input('context'),
            'link' => $link,
            'link_tip' => $link_tip,
            'created_at' => $_SERVER['REQUEST_TIME'],
            'updated_at' => $_SERVER['REQUEST_TIME']
        ]);

        if ($msg) {
            Artisan::call('send:custom:msg',[
                'type' => $request->input('type'),
                'all' => $request->input('all'),
                'msg' => $request->input('context'),
                'link' => $link,
                'link_tip' => $link_tip,
                'user' => $request->input('uuid')
            ]);
            OperationLogs::createData($request,OperationLogs::CUSTOM_MSG, '自定义消息');
            return $this->toJson(self::SUCCESS, [
                'id'=>$msg,
                'user_id' => $request->input('uuid') ?: '全员',
                'context' => $request->input('context'),
                'link' => $link,
                'link_tip' => $link_tip,
                'created_at' => $_SERVER['REQUEST_TIME'],
                'updated_at' => $_SERVER['REQUEST_TIME']
            ]);
        }

        return $this->toJson(self::ERROR);
    }
}
